from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ProcessPoolExecutor
from django.conf import settings
import django
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'exam_sys.settings.prod')

django.setup()
from paper.models import *
from django.db import connections


def close_unuseful_connections():
    for conn in connections.all():
        conn.close_if_unusable_or_obsolete()


def begin_exam(task):
    close_unuseful_connections()
    student_papers = task.studentOfTask.all()
    for paper in student_papers:
        StudentPaper.objects.filter(pk=paper.id).update(status=1)


def end_exam(task):
    close_unuseful_connections()
    student_papers = task.studentOfTask.all()
    for paper in student_papers:
        StudentPaper.objects.filter(pk=paper.id).update(status=2)


timezone = settings.TIME_ZONE
scheduler = BackgroundScheduler(timezone=timezone)

executors = {
    'default': {'type': 'threadpool', 'max_workers': 30},
    'processpool': ProcessPoolExecutor(max_workers=4)
}
job_defaults = {
    'coalesce': False,
    'max_instances': 30
}
scheduler.configure(executors=executors, job_defaults=job_defaults, timezone=timezone)
